package com.summer.web.v1.service.impl;

import com.summer.common.lib.core.exception.HibernateValidatorException;
import com.summer.web.v1.dao.UserDao;
import com.summer.web.v1.pojo.User;
import com.summer.web.v1.service.UserService;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserServiceImpl implements UserService {

    Logger logger = Logger.getLogger(UserServiceImpl.class.getName());

    @Resource(name = "bean/Validator")
    private Validator validator;
    @Resource(name = "bean/UserDao")
    private UserDao userDao;

    @Override
    public boolean insertUser(String name, String password, String email, String phoneNumber) {

        User user = new User();
        user.setEmail(email);
        user.setName(name);
        user.setPassword(password);
        user.setPhoneNumber(phoneNumber);
        Set<ConstraintViolation<User>> validate = validator.validate(user);
        if (validate.size() > 0) {
            throw new HibernateValidatorException(validate.iterator().next().getMessage());
        }
        try {
            return userDao.insertUser(user);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "新增用户失败: " + e.getMessage());
        }
        return false;
    }

    @Override
    public List<User> selectAll() {
        return userDao.selectAllUsers();
    }
}
